package com.example.client.javaapi;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author Creared by wangyang on 2019-01-28 16:07
 * email:techyang.wangy.@ymm56.com
 */
public class JavaAPIClient implements Watcher {


    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ZooKeeper zkClient = ZookeeperFactory.newZookeeper(5000, new JavaAPIClient());
        if (null == zkClient) {
            System.out.println("Zookeeper session created failure...");
            return;
        }
        System.out.println("State:" + zkClient.getState());
        try {
            COUNT_DOWN_LATCH.await();
        } catch (InterruptedException ignore) {
        }
        System.out.println("Zookeeper session established.");
        System.out.println("Zookeeper start create node");
        String pathTest = zkClient.create("/zk_test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("Success created znode :" + pathTest);
        String pathEphTest = zkClient.create("/zk_test_ephemeral", "test_ephemeral".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println("Success created znode :" + pathEphTest);

    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("Receive watched event :" + watchedEvent.toString());
        if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
            COUNT_DOWN_LATCH.countDown();
        }
    }
}
